/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.testdriver.conditions;

import org.testis.testdriver.TestPlanGlobalsHashMap;
import org.testis.testdriver.TestStepGlobalDataHashMap;
import org.testis.testdriver.translation.AtofValueTranslateService;
import org.testis.testdriver.translation.UnidentifiedTranslationException;
import java.util.Iterator;
import java.util.LinkedList;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 *
 * @author barisergun
 */
public class ConditionEvaluatingService {

    public static void evaluateConditions(ConditionEvaluatable element) {


        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine jsEngine = manager.getEngineByName("js");
        LinkedList<String> conditions = element.getConditions();
        Boolean result = true;
        Boolean inresult;
        String exception = "";

        AtofValueTranslateService service = new AtofValueTranslateService(
                TestPlanGlobalsHashMap.createInstance().getTestplanglobals(),
                TestPlanGlobalsHashMap.createInstance().getTestplanlanguages(),
                TestPlanGlobalsHashMap.createInstance().getTestplandutvalues(),
                TestStepGlobalDataHashMap.createInstance().getTeststepglobals());

        if (conditions != null) {
            for (Iterator<String> it = conditions.iterator(); it.hasNext();) {
                String foundString = it.next();
                try {
                    inresult = (Boolean) jsEngine.eval(
                            service.translateValue(foundString));

                } catch (ScriptException eee) {
                    exception = eee.getMessage();
                    inresult = false;
                } catch (UnidentifiedTranslationException eee) {
                    exception = eee.getMessage();
                    inresult = false;
                }
                if (!inresult) {
                    String toInsert = foundString + " -> "
                            + inresult + " " + exception;
                    if(!element.getFailedConditions().contains(toInsert)){
                        element.getFailedConditions().add(toInsert);                    }

                }
                result &= inresult;
            }

        } else { //if(conditions != null)
            // If there is no condition than the result of evaluation TRUE
        }
    }
}
